package com.twxm.breed.util;

import com.alibaba.fastjson.JSONObject;
import com.twxm.breed.entity.AccessToken;
import com.twxm.breed.entity.ResultTemplateDate;
import com.twxm.breed.service.LoginInfoService;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WXMsgSender {
    public static LoginInfoService loginInfoService;
    public static String template_id = "95aUBTXW6IPyH1rMRY4FP5-vA8odXN1ZQoNdP22Jnlk";
    public static String url = "www.baidu.com";

    private static WXMsgSender instance;

    private String accessToken = null;
    public static WXMsgSender getInstance(){
        if(instance == null){
            instance = new WXMsgSender();
        }
        return instance;
    }


    public JsonResult sendMsg(JSONObject data) throws IOException {
        List<String> openIdList = loginInfoService.getOpenIds();
        // Get AccessToken
        String accessToken = getAccessToken();
        if (accessToken.equals("")) {
            return new JsonResult(ResultCode.FAIL, "无法通过APPID和APPSecret获取AccessToken");
        }
        System.out.println("AccessToken = " + accessToken);
        // WeiXin Push Message URL
        String pushMessageUrl = WebChatUtil.SEND_TEMPLAYE_MESSAGE_URL + getAccessToken();
        // Get Mobile Array List

        ArrayList<String> sendSuccessUsers = new ArrayList<String>();
        ArrayList<String> sendFailUsers = new ArrayList<String>();

        if (null == template_id || template_id.equals("")) {
            return new JsonResult(ResultCode.DATANOTFOUND, "无法从PushMessageEntity获取template_id");
        }
        if (null == url || url.equals("")) {
            return new JsonResult(ResultCode.DATANOTFOUND, "无法从PushMessageEntity获取url");
        }
        JSONObject params = generatePushTemplate(data, template_id);
        if (params.size() == 0) {
            return new JsonResult(ResultCode.EXCEPTION, "generatePushTemplate()失败");
        }

        HttpPost httpPost = new HttpPost(pushMessageUrl);
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 装配post请求参数
        for (String openid : openIdList) {
            params.put("touser", openid);

            String urlParams = new String(params.toJSONString().getBytes("UTF-8"));

            StringEntity myEntity = new StringEntity(urlParams, ContentType.APPLICATION_JSON);
            System.out.println("Push Message urlParams = " + urlParams);

            httpPost.setEntity(myEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            String resultStr = "发送失败";
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 发送成功
                String resutlEntity = EntityUtils.toString(httpResponse.getEntity());
                ResultTemplateDate resultTemplateDate = JSONObject.parseObject(resutlEntity, ResultTemplateDate.class);
                if (resultTemplateDate.getErrcode().equals("40037")) {
                    resultStr = "template_id不正确";
                    sendFailUsers.add(openid);
                }
                if (resultTemplateDate.getErrcode().equals("41028")) {
                    resultStr = "form_id不正确，或者过期";
                    sendFailUsers.add(openid);
                }
                if (resultTemplateDate.getErrcode().equals("41029")) {
                    resultStr = "form_id已被使用";
                    sendFailUsers.add(openid);
                }
                if (resultTemplateDate.getErrcode().equals("41030")) {
                    resultStr = "page不正确";
                    sendFailUsers.add(openid);
                }
                if (resultTemplateDate.getErrcode().equals("45009")) {
                    resultStr = "接口调用超过限额（目前默认每个帐号日调用限额为100万）";
                    sendFailUsers.add(openid);
                }
                resultStr = "ok";
                sendSuccessUsers.add(openid);
//				return resultStr;
            } else {
                // 发送失败
                sendFailUsers.add(openid);
            }
            System.out.println("resultStr" + resultStr);
        }
        JsonResult jsonResult = new JsonResult();
        if (sendFailUsers.isEmpty()) {
            jsonResult.setCode(ResultCode.SUCCESS);
            jsonResult.setMessage("全部USER通知发送成功");
        }else {
            jsonResult.setCode(ResultCode.FAIL);
            jsonResult.setMessage("USER微信通知发送失败");
        }
        HashMap<String, Object> sendMessageResult = new HashMap<String, Object>();
        sendMessageResult.put("sendSuccessUsers", sendSuccessUsers);
        sendMessageResult.put("sendFailUsers", sendFailUsers);
        jsonResult.setData(sendMessageResult);
        return jsonResult;
    }


    private JSONObject generatePushTemplate(JSONObject data, String template_id) {
        JSONObject p = new JSONObject();

        String pondId = data.getString("pondId");
        JSONObject pd = new JSONObject();
        pd.put("value", pondId);
        pd.put("color", "#FF0000");
        p.put("pondId", pd);

        String oxygen = data.getString("oxygen");
        JSONObject od = new JSONObject();
        od.put("value", oxygen);
        od.put("color", "#FF0000");
        p.put("oxygen", od);

        String upper = data.getString("upper");
        JSONObject ud = new JSONObject();
        ud.put("value", upper);
        ud.put("color", "#FF0000");
        p.put("upper", ud);


        String lower = data.getString("lower");
        JSONObject ld = new JSONObject();
        ld.put("value", lower);
        ld.put("color", "#FF0000");
        p.put("lower", ld);

        JSONObject j = new JSONObject();
        j.put("template_id", template_id);
        j.put("topcolor", "#FF0000");
        j.put("data", p);

        return j;

    }

    private String getAccessToken() {
        if(this.accessToken != null){
            return this.accessToken;
        }
        CloseableHttpClient httpCilent = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(WebChatUtil.ACCESS_TOKEN_URL);
        try {
            HttpResponse httpResponse = httpCilent.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String entity = EntityUtils.toString(httpResponse.getEntity());
                AccessToken accessTokenObj = JSONObject.parseObject(entity, AccessToken.class);
                this.accessToken = accessTokenObj.getAccess_token();
                return this.accessToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                httpCilent.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
